package net;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class MyServer {
    public static void main(String[] args) {
        ServerSocket ss = null;
        Socket socket=null;
        InputStream in=null;
        BufferedReader reader=null;
        OutputStream out=null;

        try {
            ss=new ServerSocket(9999);
            System.out.println("服务器启动");

            socket=ss.accept();
            System.out.println("服务器连接成功");

            //通过socket对象发送数据
            in=socket.getInputStream();
            //字节流--->字符流
            reader=new BufferedReader(new InputStreamReader(in));
            String str=null;
            while((str=reader.readLine())!=null){
                if (str.equals("bye")) // 添加结束标志
                    break;
                System.out.println("服务器接受到客户端的信息是:"+str);
            }
            socket.shutdownInput();

            //向客户端发送信息
            out=socket.getOutputStream();
            out.write("服务器发送消息".getBytes());
            socket.shutdownOutput();

        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                if (out != null)
                    out.close();
                if (in != null)
                    in.close();
                if (socket != null)
                    socket.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
